package view.Core;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import method.searchSQL.*;
//import method.modifySQL.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

public class MainTestActivityUpdate extends Activity implements
		AdapterView.OnItemSelectedListener {
	private Button buttonUpdate;
	private TextView textViewDist;
	private String databaseURL;
	private String x, y;
	orderTreeID oID;

	statusControl i = new statusControl();
	ArrayList statusSpinneritems = new ArrayList();

	distControl d = new distControl();
	ArrayList distSpinneritems = new ArrayList();

	typeControl t = new typeControl();
	ArrayList typeSpinneritems = new ArrayList();

	criteriaControl c = new criteriaControl();
	ArrayList criteriaSpinneritems = new ArrayList();

	//insertTree it;
	
	EditText editTreeID, editDBH, editHeight, editCrownSpread, editEstimatedAge, editLocation, editLongitude, editLatitude;
	TextView selection;
	
	String URL;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.update_menu);

		editTreeID = (EditText) findViewById(R.id.editTreeID);
		editDBH = (EditText) findViewById(R.id.editDBH);
		editHeight = (EditText) findViewById(R.id.editHeight);
		editCrownSpread = (EditText) findViewById(R.id.editCrownSpread);
		editEstimatedAge = (EditText) findViewById(R.id.editEstimatedAge);
		editLocation = (EditText) findViewById(R.id.editLocation);
		editLongitude = (EditText) findViewById(R.id.editLongitude);
		editLatitude = (EditText) findViewById(R.id.editLatitude);
		
		selection = (TextView) findViewById(R.id.selection);
		final Spinner spin = (Spinner) findViewById(R.id.statusSpinner);
		final Spinner distSpin = (Spinner) findViewById(R.id.distSpinner);
		final Spinner typeSpin = (Spinner) findViewById(R.id.typeSpinner);
		final Spinner criteriaSpin = (Spinner) findViewById(R.id.criteriaSpinner);
		Button buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
///get new tree ID[[
		//editTreeID.setText("ghfh");
		buttonUpdate.setText("UPDATE");
		//String url = getResources().getString(R.string.serverURL);
		//oID.setNewTreeID(url);
	
		try {
			
			String url = getResources().getString(R.string.serverURL)+"id.php";
			selection.setText(url);
        	
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			HttpResponse response = client.execute(request);

			String line = "";
			String reply = "";
			
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(response.getEntity()
							.getContent()));
			while ((line = reader.readLine()) != null) {
				reply += line;
			}
			reader.close();
			try {

				editTreeID.setText(reply);

			} catch (Exception e) {
				editTreeID.setText("Input Error! Please Check set up is Correct");
			}
		} catch (Exception e) {
			editTreeID.setText("Please Check network connection");
		}
		
		
///get new treeID ]]
		
		

		
		
		URL = getResources().getString(R.string.serverURL)
				+ "insert.php";

		
		// /status[
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getStatus.php";

		i.addStatus(databaseURL);
		
		for (int spinnerI = 0; spinnerI < i.getSize(); spinnerI++) {
			statusSpinneritems.add(i.getStatus(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> statusAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, statusSpinneritems);
		statusAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spin.setAdapter(statusAA);
		// /]status

		// /dist[
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getDist.php";
		d.addDist(databaseURL);

		for (int spinnerI = 0; spinnerI < d.getSize(); spinnerI++) {
			distSpinneritems.add(d.getDist(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> DistAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, distSpinneritems);
		DistAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		distSpin.setAdapter(DistAA);
		// /]dist

		// /[type
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getType.php";
		t.addType(databaseURL);

		for (int spinnerI = 0; spinnerI < t.getSize(); spinnerI++) {
			typeSpinneritems.add(t.getType(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> TypeAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, typeSpinneritems);
		TypeAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpin.setAdapter(TypeAA);
		// /]type

		// /[criteria
		databaseURL = getResources().getString(R.string.serverURL)
				+ "getCriteria.php";
		c.addCriteria(databaseURL);

		for (int spinnerI = 0; spinnerI < c.getSize(); spinnerI++) {
			criteriaSpinneritems.add(c.getCriteria(spinnerI));
		}

		spin.setOnItemSelectedListener(this);
		ArrayAdapter<String> CriteriaAA = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, criteriaSpinneritems);
		CriteriaAA.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		criteriaSpin.setAdapter(CriteriaAA);
		// /]criteria

		buttonUpdate.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
				String inputTreeID;
				int inputDBH, inputHeight, inputCrownSpread, inputEstimatedAge;
				String inputLocation;
				double inputLongitude, inputLatitude;
				// String x = new String(""+spin.getSelectedItem());
				// String x = new String("" + spin.getSelectedItem());

				
				try {
					// String url =
					// "http://192.168.1.101/oldTreeWeb/getJsonField.php?Name=Tree tat";

					//String input = editURL.getText().toString();
					String inputstatusID = new String(i.searchStatusIDByStatus(""
							+ spin.getSelectedItem()));
					String inputdistID = new String(d.searchdistIDBydistName(""
							+ distSpin.getSelectedItem()));
					String inputtypeID = new String(t.searchTypeIDByTypeName(""
							+ typeSpin.getSelectedItem()));
					String inputcriteriaID = new String(c.searchCriteriaIDBycriteria(""
							+ criteriaSpin.getSelectedItem()));
					Toast.makeText(MainTestActivityUpdate.this,
							inputstatusID + '\n' + inputdistID + '\n' + inputtypeID + '\n' + inputcriteriaID,
							Toast.LENGTH_LONG).show();

					
					inputTreeID = editTreeID.getText().toString();
					inputDBH = Integer.parseInt(editDBH.getText().toString()); 
					inputHeight = Integer.parseInt(editHeight.getText().toString()); 
					inputCrownSpread = Integer.parseInt(editCrownSpread.getText().toString()); 
					inputEstimatedAge = Integer.parseInt(editEstimatedAge.getText().toString());
					inputLocation = editLocation.getText().toString();
					inputLongitude = Double.parseDouble(editLongitude.getText().toString()); 
					inputLatitude = Double.parseDouble(editLatitude.getText().toString());
					
					String url = getResources().getString(R.string.serverURL) +
							"insert.php?" +
							"treeID=" + inputTreeID +
							"&registrationDate=2012-2-1" + 
							"&location=" + inputLocation +
							"&longitude=" + inputLongitude +
							"&latitude=" + inputLatitude +
							"&dbh=" + inputDBH +
							"&height=" + inputHeight +
							"&crownSpread=" + inputCrownSpread +
							"&estimatedAge=" + inputEstimatedAge + 
							"&lastinspectionDate=123" +
							"&typeID=" + inputtypeID +
							"&distNo=" + inputdistID +
							"&statusID=" + inputstatusID +
							"&crID=" + inputcriteriaID;

					HttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(url);
					HttpResponse response = client.execute(request);

					String line = "";
					String reply = "";
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(response.getEntity()
									.getContent()));
					while ((line = reader.readLine()) != null) {
						reply += line;
					}
					selection.setText(reply);
					reader.close();
	
				} catch (Exception e) {
					selection.setText("Please check all the Text view");
				}
				/*
				it.insert(URL, inputTreeID, inputDBH, inputHeight, inputCrownSpread,
						inputEstimatedAge, inputLocation, inputLongitude, inputLatitude,
						inputstatusID, inputdistID, inputtypeID, inputcriteriaID);
				
				formatString = null;
				// formatString += String.format("%4d %-12s %-9s %3d\n",
				// statusID, distID);
				formatString =  editTreeID.getText().toString()+
				  				editDBH.getText().toString() + editHeight.getText().toString()  
				  				+editCrownSpread.getText().toString() + editEstimatedAge.getText().toString() 
				  				+editLocation.getText().toString() + editLongitude.getText().toString() + editLatitude.getText().toString()
								+'\n'+inputstatusID + inputdistID + inputtypeID + inputcriteriaID;
				editDBH.getText().toString();
				selection.setText(formatString);
				*/

			}
		}

		);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}
}
